<?php

require_once("gadgetPrefs.php");
require_once("debug.php");
require("messageBundles.php");

    //**
    //Write out gadgets user preference javascript declarations based on gadget header info
    //i.e. __UP_title = "Gadget Title";
    //**

    function isUsingExternalGadgetFiles()
    {
        $useExternal = ($GLOBALS['gadgetHtml'] != "") &
			            ($GLOBALS['gadgetCss'] != "") &
			            ($GLOBALS['gadgetJs'] != "");

        debugMsg("Using external gadget files " . $useExternal);
        return $useExternal;
    }

	function writeUserPrefsJs($gadget)
	{
	            /**
				Init User Prefs default values
				**/

				foreach ($gadget->UserPref as $up)
				{
					$name = ((string)$up['name']);
					$value = $up['default_value'];

					//Override default UP value with one specified in query string
					//@$qValue = $_GET["up_" . $name];
					@$qValue = $GLOBALS['_GET']["up_" . $name];
					if ((isset($qValue)) && ($qValue != ""))
					{
						$value = $qValue;
					}

					echo "\t__UP_" . $name . "__ = ";

					switch((string) $up['datatype'])
					{
						// Get attributes as element indices
						case 'list':
							echo "[";
							
							$list = split("\|", $value);
							for ($i = 0; $i < count($list); $i++)
							{
								echo "'" . $list[$i] . "'";
								if ($i+1 < count($list))
								{
									echo ",";
								}
								else
								{
									echo "]";
								}
							}
							
							break;
						
						case 'bool':
							echo $value;

							break;

						case 'enum':
						case 'hidden':
						default:
							echo "'" . $value . "'";
					}

					echo ";\r\n";
				}
	}

	function writeGadget($gadget, $moduleId)
	{
?>
        <div id="m_<?php echo $moduleId;?>" class="modbox<?php echo (@$_GET['pinSettings'] == 1) ? "_e" : "";?> ">
            <h2 class="modtitle">
                <a class="delbox" href="javascript:void(0)" onclick="return _del('<?php echo $moduleId; ?>',32,'n_32=url%3Dhttp://myearnings.googlecode.com/svn/trunk/MyEarnings.xml%26up_salaryH%3D20000%26up_salary%3D********%26up_timerPaused%3D1%26up_timerStart%3D6422');"></a><a class="minbox" id="m_<?php echo $moduleId;?>_zippy" href="javascript:void(0)" onclick="this.blur();return _zm('<?php echo $moduleId; ?>', '32');return false;"></a>
                <a class="ddbox" id="DD_tg_<?php echo $moduleId;?>" href="javascript:void(0)" onclick="this.blur(); var e=_gel('m_<?php echo $moduleId;?>'); e.className = e.className == 'modbox' ? 'modbox_e' : 'modbox'"></a>

                <span class="my_gadget" style="display:none"></span>

                <div id="m_<?php echo $moduleId;?>_h">
                    <a class="mtlink" id="m_<?php echo $moduleId;?>_url" href="<?php echo @$gadget->ModulePrefs['title_url'];?>">
                        <span id="m_<?php echo $moduleId;?>_title" class="modtitle_text">
<?php
					if (isset($gadgetTitle))
					{
						echo $gadgetTitle;
					}
					else
					{
						$useTitle = ((string)$gadget->ModulePrefs['title']);
?>
						<script>
							try
							{
								if(eval("<?php echo $useTitle; ?>"))
								{
									document.write(eval("<?php echo $useTitle; ?>"));
								}
								else
								{
									document.write("<?php echo $useTitle; ?>");
								}
							}
							catch (err)
							{
								document.write("<?php echo $useTitle; ?>");
							}
						</script>
<?php
					}
?>	
				</span>
			</a>
		</div>
<!-----Begin gadget prefs----->
<?php
    //Insert the gadget edit prefs pane here
    writeGadgetPrefs($gadget, $moduleId);
?>
<!-----End gadget prefs----->
	</h2>
	<div id="m_<?php echo $moduleId;?>_b" class="modboxin">

		<!-- Copyright 2007 and beyond, Google Inc.  To use gadgets on your own site, visit http://www.google.com/webmasters/gadgets.  To create your own gadgets, visit http://www.google.com/apis/gadgets -->
		<div id=remote_<?php echo $moduleId;?> style="border:0;padding:0;margin:0;width:100%;;overflow:hidden;">
<?php
                //Do message bundle substitution
                //TODO: Make a nice function and correctly handle multiple bundles
                $messageFile = ((string)$gadget->ModulePrefs->Locale['messages']);
				

                //If gadget spec uses three separte files for JS, HTML and CSS then write them in instead of gadget body
				if (isUsingExternalGadgetFiles() == 1)
				{
				    replaceMessageInExternalFiles($messageFile);

                    $gadgetContent = "\r\n<script>\r\n" .
                                    $GLOBALS['gadgetJs'] .
                                 "\r\n</script>\r\n" .
                                  $GLOBALS['gadgetHtml'] .
                                 "\r\n<style>\r\n" .
                                    $GLOBALS['gadgetCss'] .
                                 "\r\n</style>\r\n";

                    debugMsg ("-------------------------------------------");

                    $normalGadget = $gadget;
                    $normalGadgetBody = "\r\n<![CDATA[" . $gadgetContent . "\r\n]]>\r\n";
                    //$normalGadget->Content = $normalGadgetBody;
                    $normalGadget->Content = "%gadgetcontent%";
                    $normalGadgetString = $normalGadget->asXml();
                    $normalGadgetString = str_replace("%gadgetcontent%", $normalGadgetBody, $normalGadgetString);

                    $fileName = $GLOBALS['generatedDir'].$GLOBALS['gadgetFileName'];
                    //echo $fileName;
                    chmod($fileName, 0755);
                    $fhg = fopen($fileName, 'w') or die("Can't open file: ".$fileName);
                    $contents = fwrite($fhg, $normalGadgetString);
				}
				else
				{
				    $gadgetContentType = ((string)$gadget->Content['type']);
				    debugMsg("Gadget content type: " . $gadgetContentType);
				    if ($gadgetContentType == "url")
				    {
				        $href = ((string)$gadget->Content['href']);
				        debugMsg("Gadget source href: " . $href);
				        //$gadgetContent = get($href);
				        $gadgetContent = "<iframe width='100%' src='".$href."'>&nbsp;</iframe>"; 

				    }
				    else
				    {
				        $gadgetContent = $gadget->Content;
				    }
				    $gadgetContent = replaceMessageInGadget($messageFile, $gadgetContent);
				}
				
				$gadgetContent = str_replace("__MODULE_ID__", "0", $gadgetContent);

                //Substitute all __UP_whatever__ for their actual values
                $gadgetContent = replaceUserPrefs($gadget, $gadgetContent);

                //proxy all in-gadget requests
                //if ($GLOBALS['forceProxyForGadgetResources'] == true)
                $proxySetting = 0;
                $proxySetting = @$GET['useProxy'];

                $offline = 0;
                $offline = @$_GET['offline'];

                $qString =  ($offline == 1) ? "offline=".$offline : "";
                $qString += ($proxySetting == 1) ? "&useProxy=".$proxySetting : "";

                if ($proxySetting == 1)
                {
                    $debugMsg("PROXY: ". $proxySetting ."Forcing all in-gadget resource request through local proxy");
                    $gadgetContent = str_replace("http://", $GLOBALS['IGLocalDir']."proxy.php?".$qString."&url=http://", $gadgetContent);
                }
?>
<!-----Begin gadget body----->
				<?php echo $gadgetContent;?>
<!-----End gadget body----->				
			</div>
		</div>
    </div>
<?php
	}
?>